//go:build windows
// +build windows

package gpio

import (
	"errors"
	"io/ioutil"
	"os"
	"strings"
)

// pin represents a GPIO pin.
type pin struct {
	number        int      // the pin number
	numberAsBytes []byte   // the pin number as a byte array to avoid converting each time
	modePath      string   // the path to the /direction FD to avoid string joining each time
	edgePath      string   // the path to the /edge FD to avoid string joining each time
	valueFile     *os.File // the file handle for the value file
	callback      IRQEvent // the callback function to call when an interrupt occurs
	initial       bool     // is this the initial epoll trigger?
	err           error    //the last error
}

// OpenPin exports the pin, creating the virtual files necessary for interacting with the pin.
// It also sets the mode for the pin, making it ready for use.
func OpenPin(n int, mode Mode) (Pin, error) {
	return nil, errors.New("not implement")
}

// write opens a file for writing, writes the byte slice to it and closes the
// file.
func write(buf []byte, path string) error {
	file, err := os.OpenFile(path, os.O_WRONLY, 0600)
	if err != nil {
		return err
	}
	if _, err := file.Write(buf); err != nil {
		return err
	}
	return file.Close()
}

// read opens a file for reading, reads the bytes slice from it and closes the file.
func read(path string) ([]byte, error) {
	return ioutil.ReadFile(path)
}

// Close destroys the virtual files on the filesystem, unexporting the pin.
func (p *pin) Close() error {
	return errors.New("not implement")
}

// Mode retrieves the current mode of the pin.
func (p *pin) Mode() Mode {
	var mode string
	return Mode(mode)
}

// SetMode sets the mode of the pin.
func (p *pin) SetMode(mode Mode) {
	p.err = p.setMode(mode)
}

func (p *pin) GetMode() Mode {
	currentMode, _ := read(p.modePath)
	currentMode_ := strings.Trim(string(currentMode), "\n ")
	return Mode(currentMode_)
}

func (p *pin) setMode(mode Mode) error {
	if p.GetMode() != mode {
		return write([]byte(mode), p.modePath)
	} else {
		return nil
	}
}

// Set sets the pin level high.
func (p *pin) Set() {

}

// Clear sets the pin level low.
func (p *pin) Clear() {

}

// Get retrieves the current pin level.
func (p *pin) Get() bool {
	return false
}

// Watch waits for the edge level to be triggered and then calls the callback
// Watch sets the pin mode to input on your behalf, then establishes the interrupt on
// the edge provided

func (p *pin) BeginWatch(edge Edge, callback IRQEvent) error {
	return errors.New("not implement")
}

// EndWatch stops watching the pin
func (p *pin) EndWatch() error {
	return errors.New("not implement")

}

// Wait blocks while waits for the pin state to match the condition, then returns.
func (p *pin) Wait(condition bool) {
	panic("Wait is not yet implemented!")
}

// Err returns the last error encountered.
func (p *pin) Err() error {
	return p.err
}
